<template>
  <a-table
    rowKey="id"
    size="middle"
    bordered
    :loading="loading"
    :columns="columns"
    :dataSource="tableDataWithTotals"
    :pagination="false"
  >
    <template slot="htmlSlot" slot-scope="text">
      <div v-html="text"></div>
    </template>

    <template slot="imgSlot" slot-scope="text,record">
      <div style="font-size: 12px;font-style: italic;">
        <span v-if="!text">无图片</span>
        <img v-else :src="getImgView(text)" :preview="record.id" alt="" style="max-width:80px;height:25px;"/>
      </div>
    </template>

    <template slot="fileSlot" slot-scope="text">
      <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
      <a-button
        v-else
        ghost
        type="primary"
        icon="download"
        size="small"
        @click="downloadFile(text)"
      >
        <span>下载</span>
      </a-button>
    </template>
  </a-table>
</template>

<script>
import { getAction } from '@api/manage'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'

export default {
  name: 'CwJbhyhpxjhbSubTable',
  mixins: [JeecgListMixin],
  props: {
    record: {
      type: Object,
      default: null,
    }
  },
  data() {
    return {
      description: '举办会议和培训计划表内嵌列表',
      disableMixinCreated: true,
      loading: false,
      dataSource: [],
      // 需要计算合计的金额字段（共8个）
      totalFields: [
        'jfhj', 'sf', 'printingExpenses', 'boardWages',
        'carFare', 'informationFee', 'szf', 'siteFees'
      ],
      // 按“内容”字段分类的标识
      contentMap: {
        meeting: '会议', // 内容=会议
        training: '培训'  // 内容=培训
      },
      columns: [
        {
          title: '内容',
          align: 'center',
          dataIndex: 'content',
        },
        {
          title: '单位',
          align: 'center',
          dataIndex: 'unit',
        },
        {
          title: '会议、培训名称',
          align: 'center',
          dataIndex: 'conference',
        },
        {
          title: '召开理由',
          align: 'center',
          dataIndex: 'zkly',
        },
        {
          title: '会议类别',
          align: 'center',
          dataIndex: 'typeOfMeeting'
        },
        {
          title: '召开时间',
          align: 'center',
          dataIndex: 'meetingTime',
        },
        {
          title: '会议、培训地点',
          align: 'center',
          dataIndex: 'meeting',
        },
        {
          title: '会议/培训主要内容',
          align: 'center',
          dataIndex: 'pxzynr',
        },
        {
          title: '参加人数',
          align: 'center',
          dataIndex: 'numberOfParticipants',
          customRender: (text) => this.formatNumber(text, 0) // 人数保留整数
        },
        {
          title: '工作人数',
          align: 'center',
          dataIndex: 'gzrs',
          customRender: (text) => this.formatNumber(text, 0) // 人数保留整数
        },
        // 金额字段添加格式化（保留2位小数）
        {
          title: '经费合计',
          align: 'center',
          dataIndex: 'jfhj',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '宿费',
          align: 'center',
          dataIndex: 'sf',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '宿费标准',
          align: 'center',
          dataIndex: 'sfbz',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '印刷费',
          align: 'center',
          dataIndex: 'printingExpenses',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '印刷费标准 ',
          align: 'center',
          dataIndex: 'ysfbz',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '伙食费',
          align: 'center',
          dataIndex: 'boardWages',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '伙食费标准',
          align: 'center',
          dataIndex: 'hsfbz',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '交通费',
          align: 'center',
          dataIndex: 'carFare',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '交通费标准',
          align: 'center',
          dataIndex: 'jtfbz',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '资料费',
          align: 'center',
          dataIndex: 'informationFee',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '资料费标准',
          align: 'center',
          dataIndex: 'clfbz',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '师资费',
          align: 'center',
          dataIndex: 'szf',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '场地费',
          align: 'center',
          dataIndex: 'siteFees',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '备注',
          align: 'center',
          dataIndex: 'remark',
          scopedSlots: { customRender: 'htmlSlot' }
        },
      ],
      url: {
        listByMainId: '/cw/cwJbhyhpxjhbTj/queryCwJbhyhpxjhbByMainId',
      },
    }
  },
  computed: {
    // 带两条分类合计行的完整数据
    tableDataWithTotals() {
      if (!this.dataSource || this.dataSource.length === 0) return []

      // 深拷贝原始数据，避免污染原数据
      const newData = JSON.parse(JSON.stringify(this.dataSource))
      // 分别计算“会议”和“培训”的金额合计
      const meetingTotals = this.calcContentTotals(this.contentMap.meeting)
      const trainingTotals = this.calcContentTotals(this.contentMap.training)

      // 构建“会议合计”行
      const meetingTotalRow = this.buildTotalRow('会议合计', meetingTotals)
      // 构建“培训合计”行
      const trainingTotalRow = this.buildTotalRow('培训合计', trainingTotals)

      // 添加两条合计行到表格底部
      newData.push(meetingTotalRow, trainingTotalRow)
      return newData
    }
  },
  watch: {
    record: {
      immediate: true,
      handler() {
        if (this.record) {
          this.loadData(this.record)
        }
      }
    }
  },
  methods: {
    loadData(record) {
      this.loading = true
      this.dataSource = []
      getAction(this.url.listByMainId, { id: record.id })
        .then((res) => {
          if (res.success) {
            this.dataSource = res.result.records || [] // 兼容无数据场景
          }
        })
        .finally(() => {
          this.loading = false
        })
    },

    /**
     * 数字格式化通用方法
     * @param text 原始值
     * @param decimal 小数位数（金额默认2位，人数默认0位）
     */
    formatNumber(text, decimal = 2) {
      const num = Number(text)
      return isNaN(num) ? `0${decimal > 0 ? '.' + '0'.repeat(decimal) : ''}` : num.toFixed(decimal)
    },

    /**
     * 按“内容”字段分类计算合计
     * @param content 分类值（会议/培训）
     */
    calcContentTotals(content) {
      // 初始化合计为0
      const totals = this.totalFields.reduce((obj, field) => {
        obj[field] = 0
        return obj
      }, {})

      // 筛选“内容”匹配的数据并累加金额字段
      this.dataSource.forEach(item => {
        if (item.content === content) { // 匹配“会议”或“培训”
          this.totalFields.forEach(field => {
            const val = Number(item[field])
            totals[field] += isNaN(val) ? 0 : val
          })
        }
      })

      // 格式化合计结果（统一保留2位小数）
      this.totalFields.forEach(field => {
        totals[field] = totals[field].toFixed(2)
      })

      return totals
    },

    /**
     * 构建分类合计行
     * @param label 合计行标签（会议合计/培训合计）
     * @param totals 对应分类的合计数据
     */
    buildTotalRow(label, totals) {
      const totalRow = {
        id: `total_${label}_${new Date().getTime()}`, // 唯一ID，避免rowKey重复
        content: label, // 内容列显示合计标签
        unit: '',
        conference: '',
        zkly: '',
        typeOfMeeting: '',
        meetingTime: '',
        meeting: '',
        pxzynr: '',
        numberOfParticipants: '', // 人数列留空
        gzrs: '', // 人数列留空
        sfbz: '', // 标准列留空
        ysfbz: '', // 标准列留空
        hsfbz: '', // 标准列留空
        jtfbz: '', // 标准列留空
        clfbz: '', // 标准列留空
        remark: '',
        // 填充金额字段合计值
        jfhj: totals.jfhj,
        sf: totals.sf,
        printingExpenses: totals.printingExpenses,
        boardWages: totals.boardWages,
        carFare: totals.carFare,
        informationFee: totals.informationFee,
        szf: totals.szf,
        siteFees: totals.siteFees
      }
      return totalRow
    },

    // 空实现方法，避免报错
    downloadFile(text) {},
    getImgView(text) {
      return text
    }
  },
}
</script>

<style scoped>
/* 合计行样式优化，两条行区分显示 */
::v-deep .ant-table-tbody tr:nth-last-child(2),
::v-deep .ant-table-tbody tr:last-child {
  background-color: #f8fafc !important;
  font-weight: 600 !important;
  text-align: center !important;
  white-space: nowrap !important;
}
/* 会议合计行样式 */
::v-deep .ant-table-tbody tr:nth-last-child(2) {
  border-top: 2px solid #6366f1 !important;
  color: #4f46e5 !important;
}
/* 培训合计行样式 */
::v-deep .ant-table-tbody tr:last-child {
  border-top: 1px solid #a5b4fc !important;
  color: #6d28d9 !important;
}

/* 表格横向滚动和列宽优化，适配24列表格 */
::v-deep .ant-table-wrapper {
  overflow-x: auto !important;
  min-width: 1600px !important;
}
::v-deep .ant-table-column-title {
  white-space: nowrap !important;
  font-size: 11px !important;
  padding: 8px 4px !important;
}
::v-deep .ant-table-tbody td {
  white-space: nowrap !important;
  font-size: 11px !important;
  padding: 8px 4px !important;
}
::v-deep .ant-table-thead th {
  white-space: nowrap !important;
}
</style>